//
//  TTCertificateQueryResultViewController.m
//  TaoTuo
//
//  Created by admin on 2019/12/23.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTCertificateQueryResultViewController.h"
#import "TTDetailSectionLabel.h"
#import "TTCertificateQueryViewCell.h"
#import "TTCertQueryResultModel.h"
#import "YBImageBrowser.h"
#import "TTCertQueryImageViewCell.h"
#import <UIImageView+WebCache.h>

static NSString *infoCellID = @"infoCellID";
static NSString *imageCellID = @"imageCellID";

@implementation TTCertQueryModel

+ (instancetype)setModelWithLeftText:(NSString *)leftText rightText:(NSString *)rightText
{
    return [self setModelWithLeftText:leftText rightText:rightText isHidden:NO];
}

+ (instancetype)setModelWithLeftText:(NSString *)leftText rightText:(NSString *)rightText isHidden:(BOOL)isHidden
{
    TTCertQueryModel *model = [[self alloc] init];
    model.leftText = leftText;
    model.rightText = rightText;
    model.isHidden = isHidden;
    return model;
}

@end

@interface TTCertificateQueryResultViewController ()<UITableViewDelegate, UITableViewDataSource>
{
    CGFloat _imageH;
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSArray *sectionTitles;
@property (nonatomic, copy) NSString *certNo;
@property (nonatomic, strong) TTCertQueryResultModel *model;
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UIView *bottomView;

@end

@implementation TTCertificateQueryResultViewController

- (instancetype)initWithCertNo:(NSString *)certNo
{
    self = [super init];
    if (self) {
        
        self.certNo = certNo;
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"检测报告";
    
    self.sectionTitles = @[@"GIA检测报告", @"ROUND BRILLUANT", @"PROPORTIONS", @"FINISH", @"FLUORESCENCE", @"CLARITY CHARACTERISTICS", @"INSCRIPTION(S)"];
    
    [self getCertDatas];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSMutableArray *arr = self.dataArray[section];
    return arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTCertQueryModel *model = self.dataArray[indexPath.section][indexPath.row];
    if (model.leftText.length == 0) {
        
        TTCertQueryImageViewCell *cell = [tableView dequeueReusableCellWithIdentifier:imageCellID];
        NSURL *url = [NSURL URLWithString:self.model.ProportionImage ? : @""];
        [cell.pictureView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"f_placeholder_img"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            if (image == nil) return;
            CGSize imageSize = image.size;
            self->_imageH = imageSize.height * SCREEN_WIDTH / imageSize.width;
            [self.tableView beginUpdates];
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            [self.tableView endUpdates];
            
        }];
        return cell;
        
    } else {
        TTCertificateQueryViewCell *cell = [tableView dequeueReusableCellWithIdentifier:infoCellID];
        if (!model.isHidden) {
            model.isHidden = indexPath.row % 2;
        }
        cell.model = model;
        return cell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTCertQueryModel *model = self.dataArray[indexPath.section][indexPath.row];
    if (model.leftText.length == 0) {
        return _imageH;
    }
    return 24;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 34;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 34)];
    view.backgroundColor = [UIColor whiteColor];
    TTDetailSectionLabel *label = [[TTDetailSectionLabel alloc] initWithFrame:CGRectMake(10, 0, 100, view.height) title:self.sectionTitles[section]];
    [view addSubview:label];
    if (section == 0) {
        UIButton *btn = [UIButton createButtonWithFrame:CGRectMake(view.width - 70, 0, 60, view.height) image:[UIImage imageNamed:@"btn_right_arrow"] title:@"预览证书" titleColor:UIColorHex(999999) titleFont:[UIFont systemFontOfSize:12] space:0 backgroundColor:[UIColor whiteColor] target:self action:@selector(lookCertAction)];
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [view addSubview:btn];
    }
    return view;
}

///证书预览
- (void)lookCertAction
{
    NSString *urlString = self.model.CertFile;
    [TTLoginSingle lookCertificateWithUrlString:urlString];
}

- (void)getCertDatas
{
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:certQuery_api parameters:@{@"param.certNo" : self.certNo, @"param.entrance" : @2} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        
        self.model = [TTCertQueryResultModel modelWithJSON:responseObject];
        
        [self setupDatas];
        
        [self setupBottomView];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        @strongify(self)
        [self.tableView reloadData];
    } showLoadingInView:self.view];
}

- (void)setupDatas
{
    [self.dataArray removeAllObjects];
    
    NSMutableArray *arr1 = [NSMutableArray array];
    NSString *leftStr1 = [NSString stringWithFormat:@"证书编号:%@", self.model.ReportNo];
    NSString *rightStr1 = [NSString stringWithFormat:@"颁发日期:%@", self.model.CertCreateTime];
    [arr1 addObject:[TTCertQueryModel setModelWithLeftText:leftStr1 rightText:rightStr1 isHidden:YES]];
    
    NSMutableArray *arr2 = [NSMutableArray array];
    [arr2 addObject:[TTCertQueryModel setModelWithLeftText:@"尺寸" rightText:self.model.M1]];
    [arr2 addObject:[TTCertQueryModel setModelWithLeftText:@"克拉重量" rightText:[NSString stringWithFormat:@"%@ carat", self.model.DiaSize]]];
    [arr2 addObject:[TTCertQueryModel setModelWithLeftText:@"颜色等级" rightText:self.model.Color]];
    [arr2 addObject:[TTCertQueryModel setModelWithLeftText:@"净度等级" rightText:self.model.Clarity]];
    [arr2 addObject:[TTCertQueryModel setModelWithLeftText:@"切工等级" rightText:self.model.Cut]];
    
    NSMutableArray *arr3 = [NSMutableArray array];
    [arr3 addObject:[TTCertQueryModel setModelWithLeftText:@"全深比" rightText:self.model.TotalDepth]];
    [arr3 addObject:[TTCertQueryModel setModelWithLeftText:@"台宽比" rightText:self.model.TableSize]];
    [arr3 addObject:[TTCertQueryModel setModelWithLeftText:@"冠角" rightText:self.model.CrownAngle]];
    [arr3 addObject:[TTCertQueryModel setModelWithLeftText:@"冠高比" rightText:self.model.CrownHeight]];
    [arr3 addObject:[TTCertQueryModel setModelWithLeftText:@"亭角" rightText:self.model.PavilionAngle]];
    [arr3 addObject:[TTCertQueryModel setModelWithLeftText:@"亭深比" rightText:self.model.PavilionDepth]];
    [arr3 addObject:[TTCertQueryModel setModelWithLeftText:@"星小面比" rightText:self.model.StarFacetRatio]];
    [arr3 addObject:[TTCertQueryModel setModelWithLeftText:@"下腰小面比" rightText:self.model.LowerWaistFacetRatio]];
    [arr3 addObject:[TTCertQueryModel setModelWithLeftText:@"腰厚" rightText:self.model.WaistThickness]];
    [arr3 addObject:[TTCertQueryModel setModelWithLeftText:@"底尖" rightText:self.model.BottomTip]];
    //图片
    [arr3 addObject:[TTCertQueryModel new]];
    
    NSMutableArray *arr4 = [NSMutableArray array];
    [arr4 addObject:[TTCertQueryModel setModelWithLeftText:@"抛光" rightText:self.model.Polish]];
    [arr4 addObject:[TTCertQueryModel setModelWithLeftText:@"对称性" rightText:self.model.Sym]];
    
    NSMutableArray *arr5 = [NSMutableArray array];
    [arr5 addObject:[TTCertQueryModel setModelWithLeftText:@"荧光" rightText:self.model.Flour]];
    
    NSMutableArray *arr6 = [NSMutableArray array];
    [arr6 addObject:[TTCertQueryModel setModelWithLeftText:@"净度特征" rightText:self.model.ClarityCharacteristics]];
    
    NSMutableArray *arr7 = [NSMutableArray array];
    [arr7 addObject:[TTCertQueryModel setModelWithLeftText:self.model.Inscription rightText:@""]];
    
    [self.dataArray addObject:arr1];
    [self.dataArray addObject:arr2];
    [self.dataArray addObject:arr3];
    [self.dataArray addObject:arr4];
    [self.dataArray addObject:arr5];
    [self.dataArray addObject:arr6];
    [self.dataArray addObject:arr7];
    
    
    [self.tableView reloadData];
    
    
}

///查询
- (void)queryBtnClick
{
    self.certNo = [self.textField.text removeFirstAndLastBlank];
    if (self.certNo.length == 0) {
        [self.view makeToast:@"请输入证书号"];
        return;
    }
    [self getCertDatas];
    
}

///去官网
- (void)gotoWebsiteBtnClick
{
    NSURL *url = [NSURL URLWithString:self.model.GiaWebsite ? : @""];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url];
    }
}

- (void)setupBottomView
{
    if (self.bottomView) {
        return;
    }
    _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 220)];
    
    UIButton *websiteBtn = [UIButton createButtonWithFrame:CGRectMake(0, 0, self.view.width, 40) image:[UIImage imageNamed:@"btn_right_arrow"] title:@"进入GIA官网" titleColor:kMainColor titleFont:[UIFont systemFontOfSize:15] space:2 backgroundColor:[UIColor whiteColor] target:self action:@selector(gotoWebsiteBtnClick)];
    [_bottomView addSubview:websiteBtn];
    
    [LLLineUtilies addLineInView:_bottomView startPoint:CGPointMake(0, websiteBtn.bottom) endPoint:CGPointMake(websiteBtn.width, websiteBtn.bottom) lineColor:kSeparatorColor lineWidth:10];
    
    UILabel *label = [UILabel labelWithTitle:@"验证另一份证书" color:UIColorHex(333333) fontSize:15];
    label.frame = CGRectMake(40, websiteBtn.bottom + 10, 200, 30);
    [_bottomView addSubview:label];
    
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(40, label.bottom, self.view.width - 80, 40)];
    [textField setPlaceholder:@"请输入证书号" lightColor:nil darkColor:nil];
    textField.textColor = UIColorHex(333333);
    textField.font = [UIFont systemFontOfSize:15];
    textField.keyboardType = UIKeyboardTypeNumberPad;
    [_bottomView addSubview:textField];
    self.textField = textField;
    
    [LLLineUtilies addLineInView:_bottomView startPoint:CGPointMake(40, textField.bottom) endPoint:CGPointMake(_bottomView.width - 40, textField.bottom) lineColor:kSeparatorColor];
    
    UIButton *queryBtn = [UIButton createButtonWithTitle:@"查询" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:15] backgroundColor:kMainColor cornerRadius:20 target:self action:@selector(queryBtnClick)];
    queryBtn.frame = CGRectMake(40, textField.bottom + 20, _bottomView.width - 80, 40);
    [_bottomView addSubview:queryBtn];
    
    self.tableView.tableFooterView = _bottomView;
}


- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.emptyImageName = @"nodata";
        _tableView.emptyTitel = @"暂无数据";
        _tableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10);
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TTCertificateQueryViewCell class]) bundle:nil] forCellReuseIdentifier:infoCellID];
        [_tableView registerClass:[TTCertQueryImageViewCell class] forCellReuseIdentifier:imageCellID];
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.mas_topLayoutGuideBottom);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuideBottom);
        }];
    }
    return _tableView;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


@end
